package com.portal.encryption.utils;

import cn.hutool.crypto.symmetric.AES;
import lombok.extern.slf4j.Slf4j;

/**
 * hutool请求加解密工具类
 *
 * @author Amadeus
 * @date 2022/07/04
 */
@Slf4j
public class HutoolSecureUtil {

    private static final String MODE = "CBC";
    private static final String PADDING = "PKCS7Padding";

    /**
     * 加密十六进制
     *
     * @param data 明文
     * @param key  密钥
     * @param iv   iv加盐
     * @return {@link String}
     */
    public static String encryptHex(String data, String key, String iv) {
        try {
            AES aes = new AES(MODE, PADDING,
                    // 密钥，可以自定义
                    key.getBytes(),
                    // iv加盐，按照实际需求添加
                    iv.getBytes());
            return aes.encryptHex(data);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 解密str
     *
     * @param data 密文
     * @param key  密钥
     * @param iv   iv加盐
     * @return {@link String}
     */
    public static String decryptStr(String data, String key, String iv) {
        try {
            AES aes = new AES(MODE, PADDING,
                    // 密钥，可以自定义
                    key.getBytes(),
                    // iv加盐，按照实际需求添加
                    iv.getBytes());
            return aes.decryptStr(data);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static void main(String[] args) {
        String str = "{\n" +
                "\"dealerCode\":\"SZ111\",\n" +
                "\"messageType\":10,\n" +
                "\"dealerName\":\"深圳门店\",\n" +
                "\"activityId\":\"1\",\n" +
                "\"reqFrom\":1,\n" +
                "\"sendTo\":\"1\",\n" +
                "\"province\":\"浙江\",\n" +
                "\"city\":\"杭州\",\n" +
                "\"sendToPhone\":\"13857739176\",\n" +
                "\"showTime\":1655187673898,\n" +
                "\"skipType\":2,\n" +
                "\"subType\":50,\n" +
                "\"type\":2\n" +
                "}";
        String encryptHex = encryptHex(str, "F27B210AB1F6477482459B214BB4924B", "05631CF6A3334D03");
        log.info(encryptHex);
        String decryptStr = decryptStr(encryptHex, "F27B210AB1F6477482459B214BB4924B", "05631CF6A3334D03");
        log.info(decryptStr);
    }

}
